﻿using System.ComponentModel;
using System.Windows.Threading;

namespace SS.Common.Threading
{
    using System;

    public class ExecuteEx
    {
        /// <summary>
        /// Executes the action on the UI thread asynchronously.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="priority">The priority.</param>
        public static void OnUIThreadAsync(Action action, DispatcherPriority priority = DispatcherPriority.Normal)
        {
            var dispatcher = Dispatcher.CurrentDispatcher;
            dispatcher.BeginInvoke(action, priority);
        }

        /// <summary>
        /// Execute an action a background thread
        /// </summary>
        /// <param name="action">action to be performed</param>
        /// <param name="callback">action to be performed after completing</param>
        public static void OnBackgroundThread(Action action, Action callback)
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (s, e) => action();
            if (callback != null)
            {
                worker.RunWorkerCompleted += (s, e) => callback();
            }
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// Execute an action a background thread
        /// </summary>
        /// <param name="action">action to be performed</param>
        /// <param name="callback">action to be performed after completing</param>
        /// <param name="parameter">The input parameter</param>
        public static void OnBackgroundThread(Func<object, object> action, Action<object> callback, object parameter)
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (s, e) =>
            {
                e.Result = action(parameter);
            };
            if (callback != null)
            {
                worker.RunWorkerCompleted += (s, e) => callback(e.Result);
            }
            worker.RunWorkerAsync();
        }
    }
}
